package asia.yuanding.wechat.web.netty.handler.impl;

import asia.yuanding.wechat.web.netty.handler.MessageHandlerUtil;
import asia.yuanding.wechat.web.netty.handler.annotation.MessageProcessor;
import asia.yuanding.wechat.web.netty.handler.annotation.NettyMessageHandler;
import asia.yuanding.wechat.web.netty.manager.ChannelManager;
import asia.yuanding.wechat.web.netty.vo.Result;
import cn.hutool.json.JSONObject;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WebRTCHandler
 * @Author: YuanDing
 * @Date: 2025/8/17
 * @Description: 通话处理器
 */
@Data
@Slf4j
@NettyMessageHandler("call")
public class CallHandler {


    @MessageProcessor("start")
    public void start(JSONObject reqEntity, ChannelHandlerContext ctx) {
        Map<String , Object> dataMap =  (Map)reqEntity.get("data");
        String roomId = dataMap.getOrDefault("sessionId" , "").toString();
        String userId = MessageHandlerUtil.getUId(ctx);
        String targetUserId = dataMap.get("targetUserId").toString();

        // 对方在线就发送电话请求
        Channel channel = ChannelManager.getChannel(targetUserId);
        if (channel != null) {
            HashMap<String, Object> sendMap = new HashMap<>();
            sendMap.put("roomId", roomId);
            sendMap.put("userId", targetUserId);
            sendMap.put("targetUserId", userId);
            sendMap.put("type", dataMap.get("type"));
            channel.writeAndFlush(MessageHandlerUtil.getResult(Result.ok("receiveCall" ,sendMap )));
        }
    }

    @MessageProcessor("stop")
    public void stop(JSONObject reqEntity, ChannelHandlerContext ctx) {
        Map<String , Object> dataMap =  (Map)reqEntity.get("data");
        String roomId = dataMap.getOrDefault("sessionId" , "").toString();
        String userId = MessageHandlerUtil.getUId(ctx);
        String targetUserId = dataMap.get("targetUserId").toString();


        // 挂断电话通知
        Channel channel = ChannelManager.getChannel(targetUserId);
        if (channel != null) {
            HashMap<String, Object> sendMap = new HashMap<>();
            sendMap.put("roomId", roomId);
            sendMap.put("userId", targetUserId);
            sendMap.put("targetUserId", userId);
            channel.writeAndFlush(MessageHandlerUtil.getResult(Result.ok("stopCall" ,sendMap )));
        }
    }
}
